#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void *th_func(void *arg)
{
    int i = 1, sum = 0;
    for (; i < 100; ++i)
    {
        sum += i;
    }
    printf("pthread id %lx\n", pthread_self());
    return (void *)sum;
}

void out_pthread_attr_state(pthread_attr_t *attr)
{
    int state;
    if (pthread_attr_getdetachstate(attr, &state) != 0)
    {
        perror("pthread_attr_getdetachstat error!");
    }
    else
    {
        if (state == PTHREAD_CREATE_JOINABLE)
        {
            printf("pthread attr PTHREAD_CREATE_JOINABLE !\n");
        }
        else if (state == PTHREAD_CREATE_DETACHED)
        {
            printf("pthread attr PTHREAD_CREATE_DETACHED !\n");
        }
        else
        {
            printf("state error!\n");
        }
    }
}

int main()
{
    pthread_t default_pthread, detach_pthread;
    int res, err;

    pthread_attr_t pthread_attr;
    pthread_attr_init(&pthread_attr);

    out_pthread_attr_state(&pthread_attr);
    if (pthread_create(&default_pthread, &pthread_attr, th_func, NULL) != 0)
    {
        perror("pthread_create error!");
    }

    if ((err = pthread_join(default_pthread, (void *)&res)) != 0)
    {
        fprintf(stderr, "%s\n", strerror(err));
    }
    else
    {
        printf("%lx retval %d\n", default_pthread, res);
    }

    if (pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED) != 0)
    {
        perror("pthread_attr_setdetachstat error!");
    }
    out_pthread_attr_state(&pthread_attr);

    if (pthread_create(&detach_pthread, &pthread_attr, th_func, NULL) != 0)
    {
        perror("pthread_create error!");
    }

    if ((err = pthread_join(detach_pthread, (void *)&res)) != 0)
    {
        fprintf(stderr, "%s\n", strerror(err));
    }
    else
    {
        printf("%lx retval %d\n", detach_pthread, res);
    }

    pthread_attr_destroy(&pthread_attr);
    return 0;
}
